package org.budo.asr.service.aliyun;

import org.budo.asr.service.api.AbstractAsrService;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Getter
@Setter
@Slf4j
public abstract class AbstractAliyunAsrService extends AbstractAsrService {
    // 地域ID，常量内容，请勿改变
    protected static final String REGIONID = "cn-shanghai";

    protected static final String ENDPOINTNAME = "cn-shanghai";

    protected static final String PRODUCT = "nls-filetrans";

    protected static final String DOMAIN = "filetrans.cn-shanghai.aliyuncs.com";

    protected static final String API_VERSION = "2018-08-17";

    protected static final String POST_REQUEST_ACTION = "SubmitTask";

    protected static final String GET_REQUEST_ACTION = "GetTaskResult";

    // 请求参数key
    protected static final String KEY_APP_KEY = "appkey";
    protected static final String KEY_FILE_LINK = "file_link";
    protected static final String KEY_VERSION = "version";
    protected static final String KEY_ENABLE_WORDS = "enable_words";

    // 响应参数key
    protected static final String KEY_TASK = "Task";
    protected static final String KEY_TASK_ID = "TaskId";
    protected static final String KEY_STATUS_TEXT = "StatusText";
    protected static final String KEY_RESULT = "Result";

    // 状态值
    protected static final String STATUS_SUCCESS = "SUCCESS";
    protected static final String STATUS_RUNNING = "RUNNING";
    protected static final String STATUS_QUEUEING = "QUEUEING";

    private String accessKeyId;

    private String accessKeySecret;

    private String appKey;

    // 阿里云鉴权client
    private IAcsClient _acsClient;

    protected IAcsClient acsClient() {
        if (null != this._acsClient) {
            return this._acsClient;
        }

        synchronized (this) {
            if (null != this._acsClient) {
                return this._acsClient;
            }

            // 设置endpoint
            try {
                DefaultProfile.addEndpoint(ENDPOINTNAME, REGIONID, PRODUCT, DOMAIN);
            } catch (ClientException e) {
                log.error("#54", e);
            }

            // 创建DefaultAcsClient实例并初始化
            DefaultProfile profile = DefaultProfile.getProfile(REGIONID, this.getAccessKeyId(), this.getAccessKeySecret());
            return this._acsClient = new DefaultAcsClient(profile);
        }
    }

    protected CommonRequest postRequest(String url) {
        /**
         * 1. 创建CommonRequest 设置请求参数
         */
        CommonRequest postRequest = new CommonRequest();
        // 设置域名
        postRequest.setDomain(DOMAIN);
        // 设置API的版本号，格式为YYYY-MM-DD
        postRequest.setVersion(API_VERSION);
        // 设置action
        postRequest.setAction(POST_REQUEST_ACTION);
        // 设置产品名称
        postRequest.setProduct(PRODUCT);

        /**
         * 2. 设置录音文件识别请求参数，以JSON字符串的格式设置到请求的Body中
         */
        JSONObject taskObject = new JSONObject();
        // 设置appkey
        taskObject.put(KEY_APP_KEY, this.getAppKey());
        // 设置音频文件访问链接
        taskObject.put(KEY_FILE_LINK, url);
        // 新接入请使用4.0版本，已接入(默认2.0)如需维持现状，请注释掉该参数设置
        taskObject.put(KEY_VERSION, "4.0");
        // 设置是否输出词信息，默认为false，开启时需要设置version为4.0及以上
        taskObject.put(KEY_ENABLE_WORDS, false);

        // taskObject.put("auto_split", true);
        String task = taskObject.toJSONString();

        log.info("#89 submitFileTransRequest, task=" + task);

        // 设置以上JSON字符串为Body参数
        postRequest.putBodyParameter(KEY_TASK, task);

        // 设置为POST方式的请求
        postRequest.setMethod(MethodType.POST);
        return postRequest;
    }

    protected CommonResponse acsClientCommonResponse(CommonRequest request) {
        try {
            return this.acsClient().getCommonResponse(request);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    protected CommonRequest getRequest(String taskId) {
        /**
         * 1. 创建CommonRequest 设置任务ID
         */
        CommonRequest request = new CommonRequest();
        // 设置域名
        request.setDomain(DOMAIN);
        // 设置API版本
        request.setVersion(API_VERSION);
        // 设置action
        request.setAction(GET_REQUEST_ACTION);
        // 设置产品名称
        request.setProduct(PRODUCT);
        // 设置任务ID为查询参数
        request.putQueryParameter(KEY_TASK_ID, taskId);
        // 设置为GET方式的请求
        request.setMethod(MethodType.GET);
        return request;
    }
}
